#include<gui.h>
#include"desktop.h"
#include"icon.h"
#include"taskbar.h"
#include<assert.h>

gui_desktop_t desktop;

void desktop_main()
{
    gui_main();
}

void desktop_exit()
{
    taskbar_exit(); //exit taskbar
    gui_exit();
}

static void desktop_setup()
{
    //load mouse cursor
    gui_window_load_mouse_cursor(GUI_WINDOW(desktop.window),MOUSE_CURSOR_DIR);
    //load background
    desktop_load_background(BACKGROUND_IMAGE_NAME);
    //load icon
    icon_init();
    //taskbar load
    taskbar_init();
}


int desktop_init()
{
    if(gui_init(NULL,NULL)<0)
    {
        printf("[desktop] gui_init failed!\n");
        return -1;
    }

    gui_spirit_t *spirit=gui_window_create(GUI_WINDOW_POPUP);
    if(!spirit)
    {
        printf("[desktop] gui create desktop window failed!\n");
        return -1;
    }
    gui_window_set_fixed(GUI_WINDOW(spirit),true);
    assert(!gui_window_resize_to_screen(GUI_WINDOW(spirit)));
    gui_window_set_resizeable(GUI_WINDOW(spirit),false);
    gui_spirit_show(spirit);

    dprintf("[desktop app] desktop window show ok\n");

    desktop.window=spirit;
    list_init(&desktop.icon_list);
    desktop.icon_x=24;
    desktop.icon_y=24;

    desktop_setup();
    return 0;
}

int desktop_load_background(const char *path)
{
    gui_image_t *img=gui_image_load(BACKGROUND_IMAGE_NAME);
    if(!img)
        return -1;
    
    gui_surface_t *surface=gui_window_get_surface(GUI_WINDOW(desktop.window));
    assert(surface);
    gui_surface_t img_surface;
    gui_surface_init(&img_surface,img->w,img->h,(uint32_t*)img->buff);
    gui_surface_blit_scaled(&img_surface,NULL,surface,NULL);

    gui_window_flip(GUI_WINDOW(desktop.window));

    gui_image_destroy(img);
    return 0;
}

void desktop_launch(const char *path,char *arg)
{
    char *argv[3]={(char *)path,arg,NULL};
    if(!fork())
    {
        char *p=(char *)path;
        if(*p='/'&&*(p+1))
        {
            char *p=strrchr(path,'/');
            if(p)
            {
                *p='\0';
                chdir(p);
                *p='/';
            }
        }
        exit(execv(path,argv));
    }
}